<?php


namespace app\admin\controller;


use app\admin\model\Node;
use think\facade\View;
use think\Response;

class  NodeController extends Base
{

    /**
     * 节点列表
     *
     * @param Node $node
     * @return string
     */
    public function index(Node $node): string
    {
        if (request()->isAjax()) {

            $nodes = $node->getNodeList();

            $nodes = getTree(objToArray($nodes), false);

            $this->success('ok', '', $nodes);

        }

        return View::fetch();
    }

    /**
     * 节点添加
     *
     * @param Node $node
     */
    public function nodeAdd(Node $node): Response
    {

        $param = request()->param();

        $flag = $node->save($param);

        if ($flag) {
            $this->success('添加成功');
        } else {
            $this->error('添加失败');
        }

    }

    /**
     * 编辑节点
     *
     * @param Node $node
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function nodeEdit(Node $node): Response
    {
        $param = request()->param();

        $res = $node::find($param['id'])->save($param);
        $this->removeRoleCache();
        if ($res) {
            $this->success('编辑成功');
        } else {
            $this->error('编辑失败');
        }
    }

    /**
     * 节点删除
     *
     * @param Node $node
     */
    public function nodeDel(Node $node): Response
    {

        $id = request()->param('id');

        $res = $node::destroy($id);

        if ($res) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }

    }


}